package com.tgu.home_action.controller.admin;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.exception.ExcelCommonException;
import com.alibaba.fastjson.JSON;
import com.tgu.home_action.pojo.*;
import com.tgu.home_action.pojo.annotation.ApiJsonObject;
import com.tgu.home_action.pojo.annotation.ApiJsonProperty;
import com.tgu.home_action.pojo.state.ResponseState;
import com.tgu.home_action.service.CaseService;
import com.tgu.home_action.service.admin.AdminVolunteerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Api(tags = "管理员的志愿者管理")
@RestController
@RequestMapping("/admin/volunteer")
public class AdminVolunteerController {
    @Autowired
    private AdminVolunteerService adminVolunteerService;
    @Autowired
    private CaseService caseService;
    @Autowired
    private Logger logger;

    @ApiOperation("查询志愿者用户（可筛选）")
    @PreAuthorize("hasAnyRole('admin','superAdmin','districtAdmin')")
    @GetMapping
    public ResponseData<Page<VolunteerInformation>> getVolunteer(VolunteerInformation volunteerInformation) {
        System.out.println(volunteerInformation);
        System.out.println(volunteerInformation.getVolunteer());
        return adminVolunteerService.getVolunteer(volunteerInformation);
    }

    @ApiOperation("通过ID查询志愿者")
    @PreAuthorize("hasAnyRole('admin','superAdmin','districtAdmin')")
    @GetMapping("/id")
    public ResponseData<VolunteerInformation> getVolunteerById(@RequestParam Integer id) {
        return adminVolunteerService.getVolunteerById(id);
    }

    @ApiOperation("插入单个志愿者")
    @PreAuthorize("hasAnyRole('admin','superAdmin','districtAdmin')")
    @PostMapping
    public ResponseData<Object> insertVolunteer(@Validated(VolunteerInformation.insert.class) @RequestBody VolunteerInformation volunteerInformation) {
        try {
            return adminVolunteerService.insertVolunteer(volunteerInformation);
        } catch (DuplicateKeyException e) {
            logger.warn(e.getMessage());
            return new ResponseData<>("该身份证已被注册", ResponseState.VOLUNTEER_IS_EXIST.getValue());
        }
    }

    @ApiOperation("通过excel插入志愿者")
    @PreAuthorize("hasAnyRole('admin','superAdmin','districtAdmin')")
    @PostMapping("/excel")
    public ResponseData<List<VolunteerInformation>> insertVolunteerByExcel(@RequestParam(name = "file") MultipartFile file) {
        try {
            return adminVolunteerService.insertVolunteerByExcel(file);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseData<>(ResponseState.NOT_CAN_GET_FILE_STREAM.getMessage(), ResponseState.NOT_CAN_GET_FILE_STREAM.getValue());
        } catch (ExcelCommonException e) {
            e.printStackTrace();
            return new ResponseData<>(ResponseState.FILE_FORMAT_ERROR.getMessage(), ResponseState.FILE_FORMAT_ERROR.getValue());
        }
    }

    @ApiOperation("下载插入支援者的excel模板")
    @PreAuthorize("hasAnyRole('admin','superAdmin','districtAdmin')")
    @GetMapping("/excel/download")
    public void downloadVolunteerInformationTemplate(HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("志愿者信息模板", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), VolunteerInformation.class).autoCloseStream(Boolean.FALSE).sheet("志愿者信息")
                    .doWrite(new ArrayList<VolunteerInformation>());
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().println(JSON.toJSONString(new ResponseData<Object>("下载失败", ResponseState.ERROR.getValue())));
        }
    }

    @ApiOperation("查询志愿者的活跃天数(此时ID为志愿者用户ID)")
    @PreAuthorize("hasAnyRole('admin','superAdmin','districtAdmin')")
    @GetMapping("/liveness")
    public ResponseData<Integer> getVolunteerLiveNessDay(@RequestParam Integer volunteerId) {
        try {
            return adminVolunteerService.getVolunteerLiveNessDay(volunteerId);
        } catch (ParseException e) {
            e.printStackTrace();
            return new ResponseData<>(ResponseState.ERROR.getMessage(), ResponseState.ERROR.getValue());
        }
    }

    @ApiOperation("查询志愿者参与案件数(此时ID为志愿者用户ID)")
    @PreAuthorize("hasAnyRole('admin','superAdmin','districtAdmin')")
    @GetMapping("/case/totalNum")
    public ResponseData<Integer> getVolunteerTotalCaseNum(@RequestParam Integer volunteerId) {
        return adminVolunteerService.getVolunteerTotalCaseNum(volunteerId);
    }

    @ApiOperation("查询志愿者参与的已完成的案件数(此时ID为志愿者用户ID)")
    @PreAuthorize("hasAnyRole('admin','superAdmin','districtAdmin')")
    @GetMapping("/case/finishNum")
    public ResponseData<Integer> getVolunteerFinishCase(@RequestParam Integer volunteerId) {
        return adminVolunteerService.getVolunteerFinishCaseNum(volunteerId);
    }

    @ApiOperation("修改志愿者信息")
    @PreAuthorize("hasAnyRole('admin','superAdmin','districtAdmin')")
    @PutMapping
    public ResponseData<Object> updateVolunteerInfo(@Validated(VolunteerInformation.update.class) @RequestBody VolunteerInformation volunteerInformation) {
        return adminVolunteerService.updateVolunteerInfo(volunteerInformation);
    }

    @ApiOperation("修改志愿者头像")
    @PreAuthorize("hasAnyRole('admin','superAdmin','districtAdmin')")
    @PutMapping("/avatar")
    public ResponseData<Object> updateAvatar(@ApiJsonObject(name = "AdminUpdateVolunteerAvatar", value = {
            @ApiJsonProperty(key = "id", description = "志愿者信息ID"),
            @ApiJsonProperty(key = "avatarUrl", description = "头像Url")
    }) @RequestBody Map<String, Object> param) {
        Integer id = (Integer) param.get("id");
        String avatarUrl = (String) param.get("avatarUrl");
        return adminVolunteerService.updateAvatar(id, avatarUrl);
    }

    @ApiOperation("获取案件")
    @PreAuthorize("hasAnyRole('admin','superAdmin','districtAdmin')")
    @GetMapping("/case")
    public ResponseData<Page<Case>> getVolunteerCases(@Validated(Case.volunteer.class) Case nowCase) {
        return adminVolunteerService.getVolunteerCases(nowCase);
    }

    @ApiOperation("删除志愿者")
    @PreAuthorize("hasAnyRole('admin','superAdmin','districtAdmin')")
    @DeleteMapping
    public ResponseData<Object> delVolunteer(@RequestParam() Integer volunteerId) {
        return adminVolunteerService.delVolunteer(volunteerId);
    }

    @ApiOperation("查询当日活跃的志愿者的志愿者")
    @GetMapping("/liveNess")
    public ResponseData<List<Volunteer>> getLiveNessVolunteer() {
        try {
            return adminVolunteerService.getLiveNessVolunteer();
        } catch (ParseException e) {
            e.printStackTrace();
            return new ResponseData<>(ResponseState.ERROR.getMessage(), ResponseState.ERROR.getValue());
        }

    }
}
